package chapter18;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2019-03-31 21:07
 */
public class SerialCtl implements Serializable {
    private String s;
    private transient String b;

    public SerialCtl(String s, String b) {
        this.s = "not transient:" + s;
        this.b = "transient" + b;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        SerialCtl sc = new SerialCtl("test1", "test2");
        System.out.println("before:\n" + sc);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(buf);
        out.writeObject(sc);

        // now get it back
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray()));
        SerialCtl sc1 = (SerialCtl) in.readObject();
        System.out.println("after:\n" + sc1);
    }

    @Override
    public String toString() {
        return "SerialCtl{" +
                "s='" + s + '\'' +
                ", b='" + b + '\'' +
                '}';
    }

    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
        b = (String) stream.readObject();
    }

    private void writeObject(ObjectOutputStream stream) throws IOException {
        stream.defaultWriteObject();
        stream.writeObject(b);
    }
}
